package com.zhuoan.im.webapp.biz.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhuoan.im.server.service.ImgMnService;
import com.zhuoan.im.webapp.biz.GroupMemberBiz;
import com.zhuoan.im.webapp.biz.GroupsBiz;
import com.zhuoan.im.webapp.biz.UserBiz;
import com.zhuoan.im.webapp.biz.UserGroupBiz;
import com.zhuoan.im.webapp.common.GroupContant;
import com.zhuoan.im.webapp.common.ResCodeEnum;
import com.zhuoan.im.webapp.common.UserGroupContant;
import com.zhuoan.im.webapp.common.exception.BizException;
import com.zhuoan.im.webapp.dao.mapper.GroupsMapper;
import com.zhuoan.im.webapp.dao.model.GroupMember;
import com.zhuoan.im.webapp.dao.model.Groups;
import com.zhuoan.im.webapp.dao.model.UserGroup;
import com.zhuoan.im.webapp.dao.model.reqbody.GroupBody;
import com.zhuoan.im.webapp.dao.model.vo.UserVO;
import org.jim.common.packets.Group;
import org.jim.common.packets.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * GroupsBizImpl
 *
 * @author weixiang.wu
 * @date 2018-10-15 17:01
 **/
@Service
public class GroupsBizImpl implements GroupsBiz {
    private final static Logger logger = LoggerFactory.getLogger(GroupsBizImpl.class);

    @Resource
    private UserGroupBiz userGroupBiz;

    @Resource
    private GroupsMapper groupsMapper;

    @Resource
    private GroupMemberBiz groupMemberBiz;

    @Resource
    private UserBiz userBiz;

    private static final String MY_FRIEND_GROUP = "我的好友";

    @Transactional
    @Override
    public List<Group> queryGroupByCreatorUserId(Long creatorUserId) {
        List<UserGroup> userGroups = userGroupBiz.queryUserGroupByCreatorUserId(creatorUserId);
        List<Group> groups = new ArrayList<>();
        if (userGroups.size() == 0) {
            //初始化群组
            initGroups(creatorUserId, groups);
        } else {
            //根据 创建人id，查找出当前用户的所有群组
            for (UserGroup userGroup : userGroups) {
                Long groupId = userGroup.getGroupId();
                Group jimGroup = userGroupBiz.queryGroupAndInnerUserInfoByGroupId(groupId);
                groups.add(jimGroup);
            }
        }
        return groups;
    }

    @Override
    public List<Group> queryGroupByCreatorUserIdAndType(Long creatorUserId, Integer myFriends) {
        //获取对应类型的群组信息
        UserGroup userGroups = userGroupBiz.queryGroupByCreatorUserIdAndType(creatorUserId, myFriends);

        //根据群组id, 获取当前群组及组内所有用户的信息
        Group groupDetail = userGroupBiz.queryGroupAndInnerUserInfoByGroupId(userGroups.getGroupId());

        //将群组放入群组列表
        List<Group> friends = new ArrayList<>();
        friends.add(groupDetail);
        return friends;
    }

    @Override
    public Group createGroup(GroupBody groupBody) {
        String[] userIds = groupBody.getUserIds().split(",");
        List<String> ids = Arrays.asList(userIds);
        List<UserVO> userVOS = userBiz.queryUserVOByIds(stringToLongList(ids));

        //1.初始化群组
        Groups group = new Groups();
        StringBuilder sb = new StringBuilder();
        for (UserVO userVO : userVOS) {
            sb.append(userVO.getNick());
        }
        //组名:组内用户昵称相加0，50
        group.setGroupName(sb.toString().substring(0, 50));
        group.setGmtCreate(new Date());
        group.setGroupAvatar(ImgMnService.nextImg());
        Long result = groupsMapper.insertSelectiveReturnId(group);
        if (result != 1) {
            throw new BizException("插入群组表失败", ResCodeEnum.SYSTEM_EXCEPTION.getResCode());
        }
        //2.插入用户群组关系表
        UserGroup userGroup = new UserGroup();
        userGroup.setGroupId(group.getId());
        userGroup.setType(UserGroupContant.ORDINARY_GROUP);
        userGroup.setCreatorUserId(Long.valueOf(groupBody.getCreatorUserId()));
        userGroup.setGmtCreate(new Date());
        int i = userGroupBiz.insertSelective(userGroup);
        if (i != 1) {
            throw new BizException("初始化群组时,插入用户群组关系表", ResCodeEnum.SYSTEM_EXCEPTION.getResCode());
        }
        //3.同步到jim的group
        List<org.jim.common.packets.User> innerGroupUserDetail = new ArrayList<>();
        //获取当前群组内的所有用户的信息
        for (UserVO userVO : userVOS) {
            User user = transferJimUserByUserVO(userVO);
            innerGroupUserDetail.add(user);
        }
        return getJimGroup(group.getId(), innerGroupUserDetail);
    }

    @Override
    public void operateGroupMember(GroupBody groupBody) {
        switch (groupBody.getType()) {
            case GroupContant.ADD_MEMBER:
                GroupMember groupMember = new GroupMember();
                groupMember.setGmtCreate(new Date());
                groupMember.setGroupId(Long.valueOf(groupBody.getGroupId()));
                groupMember.setInGroupUserId(Long.valueOf(groupBody.getTargetId()));
                groupMember.setRemark("userId=[" + groupBody.getCreatorUserId() + "]在组内邀请了userId=" + groupBody.getTargetId() + "]");
                int i = groupMemberBiz.addGroupMember(groupMember);
                if (i != 1) {
                    logger.error("群组人员添加发生异常");
                }
                break;
            case GroupContant.REMOVE_MEMBER:
                //先查询当前这个用户是否有这个群组
                List<UserGroup> userGroups = userGroupBiz.queryUserGroupByCreatorUserId(Long.valueOf(groupBody.getCreatorUserId()));
                boolean contain = Boolean.FALSE;
                for (UserGroup userGroup : userGroups) {
                    if (userGroup.getGroupId().equals(Long.valueOf(groupBody.getGroupId()))) {
                        contain = Boolean.TRUE;
                        break;
                    }
                }
                //“包含” - > 继续往下处理
                if (contain) {
                    int j = groupMemberBiz.removeMember(groupBody.getGroupId(),groupBody.getTargetId());
                } else {
                    logger.error("当前用户没有这个群组");
                }
                break;
            default:
                break;
        }



    }


    private void initGroups(Long creatorUserId, List<Group> groups) {
        logger.info("用户id=[" + creatorUserId + "]开始初始化群组：我的好友");
        //1.初始化群组：我的好友
        Groups group = new Groups();
        group.setGroupName(MY_FRIEND_GROUP);
        group.setGmtCreate(new Date());
        group.setGroupAvatar(ImgMnService.nextImg());
        Long result = groupsMapper.insertSelectiveReturnId(group);
        if (result != 1) {
            throw new BizException("插入群组表失败", ResCodeEnum.SYSTEM_EXCEPTION.getResCode());
        }
        //2.插入用户群组关系表
        UserGroup userGroup = new UserGroup();
        userGroup.setGroupId(group.getId());
        userGroup.setType(UserGroupContant.MY_FRIENDS);
        userGroup.setCreatorUserId(creatorUserId);
        userGroup.setGmtCreate(new Date());
        int i = userGroupBiz.insertSelective(userGroup);
        if (i != 1) {
            throw new BizException("初始化群组时,插入用户群组关系表", ResCodeEnum.SYSTEM_EXCEPTION.getResCode());
        }
        //3.同步到jim的group
        Group jimGroup = new Group();
        jimGroup.setName(group.getGroupName());
        jimGroup.setAvatar(group.getGroupAvatar());
        jimGroup.setGroup_id(String.valueOf(group.getId()));
        groups.add(jimGroup);
    }


    private static List<Long> stringToLongList(List<String> inList) {
        List<Long> iList = new ArrayList<>(inList.size());
        try {
            for (String anInList : inList) {
                iList.add(Long.valueOf(anInList));
            }
        } catch (Exception ignored) {
        }
        return iList;
    }

    private org.jim.common.packets.User transferJimUserByUserVO(UserVO userVO) {
        org.jim.common.packets.User user = new org.jim.common.packets.User();
        user.setId(String.valueOf(userVO.getId()));
        user.setNick(userVO.getNick());
        user.setAvatar(userVO.getAvatar());
        user.setSign(userVO.getSign());
        user.setStatus(String.valueOf(userVO.getStatus()));
        // 扩展字段
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", userVO.getUsername());
        jsonObject.put("salt", userVO.getSalt());
        jsonObject.put("blockAddr", userVO.getBlockAddr());
        jsonObject.put("referralCode", userVO.getReferralCode());
        jsonObject.put("address", userVO.getAddress());
        jsonObject.put("sex", userVO.getSex());
        jsonObject.put("email", userVO.getEmail());
        jsonObject.put("dateOfBirth", userVO.getDateOfBirth());
        jsonObject.put("phone", userVO.getPhone());
        jsonObject.put("remark", userVO.getRemark());
        jsonObject.put("gmtCreate", userVO.getGmtCreate());
        user.setExtras(jsonObject);
        return user;
    }

    private Group getJimGroup(Long groupId, List<org.jim.common.packets.User> myFriendGroupUsers) {
        Groups groups = groupsMapper.selectByPrimaryKey(groupId);
        Group group = new Group();
        group.setGroup_id(String.valueOf(groupId));
        // 将当前群组内的所有用户的信息放入到 群组里
        group.setUsers(myFriendGroupUsers);
        group.setName(groups.getGroupName());
        group.setAvatar(groups.getGroupAvatar());
        Long online = groups.getOnline();
        group.setOnline(Math.toIntExact(online == null ? 1 : online));
        group.setCreateTime(groups.getGmtCreate().getTime());
        // 扩展字段
        JSONObject extras = new JSONObject();
        extras.put("notice", groups.getNotice());
        extras.put("qrCore", groups.getQrCore());
        group.setExtras(extras);
        return group;
    }

}
